import Vue from "vue";
import VueRouter from "vue-router";
import store from "@/store";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "Home",
    component: () => import("../views/Home"),
    // meta: {
    //   isHideFooter: false,
    // },
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("../views/Login"),
    meta: {
      isHideFooter: true,
    },
  },
  {
    path: "/register",
    name: "Register",
    /*
      路径 @ --> src
      webpack功能 alias 路径别名
      问题：路径没有提示
      解决: 增加路径提示 
        vscode有一个配置文件：jsconfig.json
    */
    component: () => import("@/views/Register"),
    meta: {
      isHideFooter: true,
    },
  },
  {
    // 可选的params参数
    path: "/search/:keyword?",
    name: "Search",
    component: () => import("@/views/Search"),
    // meta: {
    //   isHideFooter: false,
    // },
  },
  {
    path: "/detail/:id",
    name: "Detail",
    component: () => import("@/views/Detail"),
  },
  {
    path: "/addcartsuccess",
    name: "AddCartSuccess",
    component: () => import("@/views/AddCartSuccess"),
  },
  {
    path: "/shopcart",
    name: "ShopCart",
    component: () => import("@/views/ShopCart"),
  },
  {
    path: "/trade",
    name: "Trade",
    component: () => import("@/views/Trade"),
  },
  {
    path: "/pay",
    name: "Pay",
    component: () => import("@/views/Pay"),
  },
  {
    path: "/paysuccess",
    name: "PaySuccess",
    component: () => import("@/views/PaySuccess"),
  },
  {
    path: "/center",
    name: "Center",
    component: () => import("@/views/Center"),
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
  /*
    滚动行为：当你路由跳转时生效
  */
  scrollBehavior() {
    return { x: 0, y: 0 };
  },
});

const whiteList = [
  "Home",
  "Login",
  "Register",
  "Search",
  "Detail",
  "AddCartSuccess",
  "ShopCart",
];

// 定义路由全局导航守卫
router.beforeEach((to, from, next) => {
  if (whiteList.includes(to.name) || store.state.user.token) {
    next();
    return;
  }
  // console.log(to, from);
  next({
    name: "Login",
    query: {
      redirect: to.path,
    },
  });
});

export default router;
